<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" show-icon center :closable="false"></el-alert>
      <!-- 步骤条区域 -->
      <!-- active要求绑定的是数字型，所以减去0变成数字型 -->
      <el-steps :space="200" :active="activeIndex - 0 " align-center finish-status="success">
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- 表单区域 -->
      <el-form
        ref="addGoodsFormRef"
        :rules="addGoodsFormRules"
        label-position="top"
        :model="addGoodsForm"
        label-width="100px"
      >
        <!-- tab栏区域 -->
        <el-tabs
          tab-position="left"
          v-model="activeIndex"
          @tab-click="tabClicked"
          :before-leave="beforeTabLeave"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input type="text" v-model="addGoodsForm.goods_name" />
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input type="text" v-model="addGoodsForm.goods_price" />
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input type="text" v-model="addGoodsForm.goods_weight" />
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input type="text" v-model="addGoodsForm.goods_number" />
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- v-model绑定商品所属的分类数组 -->
              <el-cascader
                v-model="addGoodsForm.goods_cat"
                :options="cateList"
                :props="castProp"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyQueryList">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox v-for="(cb, i) in item.attr_vals" :key="i" :label="cb"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in onlyQueryList">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action表示图片上传的api接口 -->
            <el-upload
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headerObject"
              :on-success="handleSuccess"
              list-type="picture"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器组件区域 -->
            <quill-editor v-model="addGoodsForm.goods_introduce"></quill-editor>
            <el-button type="primary" class="btnAdd" @click="addFormBtn">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <el-dialog title="图片预览" :visible.sync="preViewVisible" width="70%">
      <img class="imgWidth" :src="preViewUrl" alt />
    </el-dialog>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      // 步骤条和tabs的索引
      activeIndex: '0',
      // 添加商品的表单
      addGoodsForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        // 商品详情描述
        goods_introduce: '',
        // 商品的参数（数组），包含 动态参数 和 静态属性
        attrs: []
      },
      // 表单校验规则
      addGoodsFormRules: {
        goods_name: [
          {
            required: true,
            message: '请输入商品名称',
            trigger: 'blur'
          }
        ],
        goods_price: [
          {
            required: true,
            message: '请输入商品价格',
            trigger: 'blur'
          }
        ],
        goods_weight: [
          {
            required: true,
            message: '请输入商品重量',
            trigger: 'blur'
          }
        ],
        goods_number: [
          {
            required: true,
            message: '请输入商品数量',
            trigger: 'blur'
          }
        ],
        goods_cat: [
          {
            required: true,
            message: '请选择商品分类',
            trigger: 'blur'
          }
        ]
      },
      // 商品分类列表
      cateList: [],
      // 级联选择器配置
      castProp: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 动态参数列表
      manyQueryList: [],
      // 静态属性列表
      onlyQueryList: [],
      // upload图片上传地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 图片上传的请求头
      headerObject: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 预览链接
      preViewUrl: '',
      preViewVisible: false
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get(`categories`)
      if (res.meta.status !== 200) {
        return this.$message({
          message: '获取参数列表失败',
          type: 'error'
        })
      }
      this.cateList = res.data
    },
    // 级联选择器选择变化函数
    handleChange () {
      // console.log(this.addGoodsForm.goods_cat)
      if (this.addGoodsForm.goods_cat.length !== 3) {
        this.addGoodsForm.goods_cat = []
      }
    },
    // tab栏切换之前调用
    beforeTabLeave (activeName, oldActiveName) {
      // console.log(activeName)
      // console.log(oldActiveName)
      if (oldActiveName === '0' && this.addGoodsForm.goods_cat.length !== 3) {
        this.$message({
          message: '请先选择商品分类',
          type: 'warning'
        })
        // 返回false阻止tab栏的切换
        return false
      }
    },
    // tab 被选中时触发
    async tabClicked () {
      // 证明点击的是动态参数面板
      if (this.activeIndex === '1') {
        // 获取动态参数列表
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'many'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message({
            message: '获取动态参数列表失败',
            type: 'error'
          })
        }
        // console.log(res.data)
        // 将res.data数组每一项的attr_vals属性转化成数组
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals === 0 ? [] : item.attr_vals.split(' ')
        })
        // console.log(res.data[0].addr_vals)

        // 保存动态参数列表
        this.manyQueryList = res.data
        // console.log(this.manyQueryList[0].attr_vals)
      } else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: 'only'
            }
          }
        )
        if (res.meta.status !== 200) {
          return this.$message({
            message: '获取静态属性列表失败',
            type: 'error'
          })
        }
        // console.log(res.data)

        this.onlyQueryList = res.data
      }
    },
    // 处理图片预览效果
    handlePreview (file) {
      // console.log(file)
      this.preViewUrl = file.response.data.url
      this.preViewVisible = true
    },
    // 处理移除图片操作
    handleRemove (file) {
      // 1.获取将要删除的图片路径
      // console.log(file)
      const filePath = file.response.data.tmp_path
      // 2.从pics数组中找到这个图片对应的索引值
      const i = this.addGoodsForm.pics.findIndex(item => {
        if (item.pic === filePath) {
          return item
        }
      })
      // 3.调用数组的splice方法，从数组中删除图片路径
      this.addGoodsForm.pics.splice(i, 1)
    },
    // 监听图片上传成功，获取图片保存路径
    handleSuccess (response) {
      // 1.拼接一个图片信息对象
      const picInfo = {
        pic: response.data.tmp_path
      }
      // 2.将图片信息添加到pics数组
      this.addGoodsForm.pics.push(picInfo)
      // console.log(this.addGoodsForm)
    },
    addFormBtn () {
      this.$refs.addGoodsFormRef.validate(async valid => {
        if (!valid) {
          return this.$message({
            message: '请填写必要的表单',
            type: 'error'
          })
        }
        // console.log(this.manyQueryList[0].attr_vals)
        // 处理动态参数
        this.manyQueryList.forEach(item => {
          const newInfo = {
            attr_value: item.attr_vals.join(' '),
            attr_id: item.attr_id
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyQueryList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals
          }
          this.addGoodsForm.attrs.push(newInfo)
        })
        // 执行添加业务
        // 因为代码中的级联选择器与form表单中的数据绑定，
        // 并且对数据类型的要求有冲突，所以在提交的时候要对表单进行深拷贝
        // 使用lodash插件的cloneDeep方法进行深拷贝
        const form = _.cloneDeep(this.addGoodsForm)
        form.goods_cat = form.goods_cat.join(',')
        // console.log(form)
        // 发起请求添加商品，商品名称必须是惟一的
        const { data: res } = await this.$http.post(`goods`, form)
        if (res.meta.status !== 201) {
          return this.$message({
            message: '添加商品失败,请检查必填项',
            type: 'error'
          })
        }
        this.$message({
          message: '添加商品成功',
          type: 'success'
        })
        this.$router.push('/goods')
      })
    }
  },
  computed: {
    // 所选分类id的计算属性
    cateId () {
      if (this.addGoodsForm.goods_cat.length === 3) {
        return this.addGoodsForm.goods_cat[2]
      }
      return null
    }
  }
}
</script>
<style lang="less" scoped>
.el-steps {
  margin: 15px 0;
}
.el-step__title {
  font-size: 13px !important;
}
.imgWidth {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>
